<template>
  <div class="body page-miH page-bgBack">
    <div style="display: flex; justify-content: space-between">
      <div class="fix-item-wrapper2">
        <div class="fix-item-two" style="border-right: 1px solid #e8e8e8">
          <div>
            <p class="remainderQuotaName">合同剩余额度</p>
            <p class="remainderQuota">
              {{ this.contractCount }}
            </p>
          </div>
        </div>
        <div class="fix-item-two">
          <div>
            <p class="remainderQuotaName">人脸剩余额度</p>
            <p class="remainderQuota">
              {{ this.faceCount }}
            </p>
          </div>
        </div>
      </div>
      <!--    配额弹窗   -->
      <a-modal title="租户配额" width="600px" :visible="showSiteQuota" @ok="confirmSiteTranche" @cancel="closeSiteTranche" cancelText>
        <template #footer>
          <a-button key="back" @click="closeSiteTranche">取消</a-button>
          <a-button key="submit" type="primary" :loading="confirmLoading" @click="confirmSiteTranche">配额</a-button>
        </template>
        <a-form :form="formSiteTranche">
          <a-form-item label="合同份额" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
            <a-input-number v-decorator="['siteContractTranche', { initialValue: 0, rules: [{ validator: this.validateTranche }] }]" />
          </a-form-item>
          <a-form-item label="人脸份额" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
            <a-input-number v-decorator="['siteFacesTranche', { initialValue: 0, rules: [{ validator: this.validateTranche }] }]" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
    <a-row type="flex" justify="space-between" style="margin: 25px 25px 25px 25px">
      <a-col>
        <a-input-search placeholder="用工单位名称" style="width: 200px" allowClear @search="onSearch" />
      </a-col>
      <a-col>
        <a-button @click="clickCertified" type="primary">新增认证印章归属企业</a-button>
      </a-col>
      <a-button @click="clickSiteTranche" type="primary">租户充值</a-button>
    </a-row>
    <a-table
      :pagination="pagination"
      :data-source="companyList"
      :row-key="(companyList) => companyList.id"
      :loading="tableLoading"
      @change="pageChange"
    >
      <a-table-column title="企业名称" data-index="companyName" align="center" />
      <a-table-column title="法人姓名" data-index="legalName" align="center" />
      <a-table-column title="社会统一信用代码" align="center">
        <template v-slot="text">
          <span @click="openLicense(text)" style="color: blue; cursor: pointer">
            {{ text.organizationRegNo }}
          </span>
        </template>
      </a-table-column>
      <a-table-column title="邮箱" data-index="email" align="center" />
      <a-table-column title="审核状态" align="center">
        <template v-slot="text">
          {{ getStatus(text) }}
        </template>
      </a-table-column>
      <a-table-column title="拒绝原因" data-index="reason" align="center" />
      <a-table-column title="操作" :width="180" align="center">
        <template v-slot="text">
          <a-button type="link" @click="reClickCertified(text)"> 重新认证 </a-button>
        </template>
      </a-table-column>
    </a-table>
    <!--    认证弹窗   -->
    <a-modal title="认证" width="600px" :visible="showCertified" @ok="confirmCertified" @cancel="closeCertified" cancelText>
      <template #footer>
        <a-button key="back" @click="closeCertified">取消</a-button>
        <a-button key="submit" type="primary" :loading="confirmLoading" @click="confirmCertified">认证</a-button>
      </template>
      <a-form :form="formCertified">
        <a-form-item label="企业名称" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-input
            v-decorator="[
              'companyName',
              { initialValue: certifiedCompany.companyName, rules: [{ required: true, message: '请输入企业名称' }] }
            ]"
            :disabled="certifiedCompany.companyName !== ''"
          />
        </a-form-item>
        <a-form-item label="组织类型" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-radio-group
            v-decorator="[
              'organizationType',
              { initialValue: certifiedCompany.organizationType, rules: [{ required: true, message: '请选择组织类型' }] }
            ]"
          >
            <a-radio value="0">企业</a-radio>
            <a-radio value="1">事业单位</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="社会统一信用代码" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-input
            v-decorator="[
              'organizationRegNo',
              { initialValue: certifiedCompany.organizationRegNo, rules: [{ required: true, message: '请输入社会统一信用代码' }] }
            ]"
            :disabled="certifiedCompany.organizationRegNo !== ''"
          />
        </a-form-item>
        <a-form-item label="营业执照图片" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-upload
            v-decorator="[
              'fileUrl',
              { initialValue: certifiedCompany.fileUrl, rules: [{ required: true, message: '请上传营业执照图片' }] }
            ]"
            list-type="picture-card"
            class="ant-upload"
            :before-upload="beforeUpload"
            :accept="'.jpg, .jpeg, .png'"
            :showUploadList="false"
          >
            <img v-if="certifiedCompany.fileUrl" :src="certifiedCompany.fileUrl" alt="营业执照图片" style="width: 100px; cursor: pointer" />
            <img v-else src="../../../assets/img/上传.png" alt="点击上传" style="width: 100px; cursor: pointer" />
          </a-upload>
        </a-form-item>
        <a-form-item label="法人姓名" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-input
            v-decorator="[
              'legalName',
              { initialValue: certifiedCompany.legalName, rules: [{ required: true, message: '请输入法人姓名' }] }
            ]"
          />
        </a-form-item>
        <a-form-item label="电子邮箱" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-input
            :disabled="certifiedCompany.email !== ''"
            v-decorator="['email', { initialValue: certifiedCompany.email, rules: [{ required: true, message: '请输入电子邮箱' }] }]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <!--    配额弹窗   -->
    <a-modal title="配额" width="600px" :visible="showQuota" @ok="confirmTranche" @cancel="closeTranche" cancelText>
      <template #footer>
        <a-button key="back" @click="closeTranche">取消</a-button>
        <a-button key="submit" type="primary" :loading="confirmLoading" @click="confirmTranche">配额</a-button>
      </template>
      <a-form :form="formTranche">
        <a-form-item label="合同份额" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-input-number v-decorator="['contractTranche', { initialValue: 0, rules: [{ validator: this.validateTranche }] }]" />
        </a-form-item>
        <a-form-item label="人脸份额" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-input-number v-decorator="['facesTranche', { initialValue: 0, rules: [{ validator: this.validateTranche }] }]" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!--    点击社会统一信用代码展示营业执照图片弹窗   -->
    <a-modal title="营业执照" width="1500px" :visible="showLicense" @cancel="closeLicense" :footer="null">
      <div class="license-container">
        <img v-if="this.licenseUrl" :src="this.licenseUrl" alt="营业执照" style="object-fit: cover" />
        <p v-else style="text-align: center">暂未上传营业执照</p>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { uploadGeneralImg } from "@/api/file/file";
import { getCompanyList, companyCertified, companyTranche, getSiteCount, siteTranche, companyCertifiedUpdate } from "./api";

export default {
  data() {
    return {
      formCertified: this.$form.createForm(this),
      formTranche: this.$form.createForm(this),
      formSiteTranche: this.$form.createForm(this),
      companyList: [],
      tableLoading: false,
      confirmLoading: false,
      query: "",
      list: [],
      showCertified: false,
      showQuota: false,
      showSiteQuota: false,
      canEditOrganizationRegNo: true,
      canEditEmail: true,
      pagination: {
        current: 1
      },
      certifiedCompany: {},
      tranche: {},
      siteTranche: {},
      // 租户合同人脸额度
      contractSum: 0,
      contractCount: 0,
      faceSum: 0,
      faceCount: 0,
      licenseUrl: "",
      showLicense: false
    };
  },
  computed: {},
  created() {
    // 页面初始化加载用工单位列表，查询租户额度
    this.getViewCompanyList();
    this.selectSiteCount();
  },
  mounted() {},
  methods: {
    openLicense(text) {
      this.showLicense = true;
      this.licenseUrl = text.fileUrl;
    },
    closeLicense() {
      this.showLicense = false;
      this.licenseUrl = "";
    },
    getStatus(text) {
      if (text) {
        switch (text.status) {
          case 0:
            return "申请中";
          case 1:
            return "通过";
          case 2:
            return "拒绝";
        }
      } else {
        return "未认证";
      }
    },
    onSearch(param) {
      this.pagination.current = 1;
      if (param) {
        this.companyList = this.companyList.filter((v) => v.companyName && v.companyName.includes(param));
      } else {
        this.getViewCompanyList();
      }
    },
    pageChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.$setPage("ygdw_condition", this.pagination.current);
    },
    // 页面加载查询用工单位列表
    getViewCompanyList() {
      this.tableLoading = true;
      getCompanyList()
        .then((res) => {
          this.companyList = res.data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    // 关闭认证弹窗
    closeCertified() {
      // 关闭模态框、清空表单信息
      this.showCertified = false;
      this.formCertified.resetFields();
    },
    validateTranche(rule, value, callback) {
      if (value < 0) {
        callback(new Error("份额不能为负数"));
      } else {
        callback();
      }
    },
    // 提交认证
    confirmCertified() {
      this.formCertified.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          this.certifiedCompany.organizationRegNo = values.organizationRegNo;
          this.certifiedCompany.companyName = values.companyName;
          this.certifiedCompany.legalName = values.legalName;
          this.certifiedCompany.email = values.email;
          this.certifiedCompany.organizationType = values.organizationType;
          // 如果有id调更新接口
          if (this.certifiedCompany.id) {
            companyCertifiedUpdate(this.certifiedCompany)
              .then((res) => {
                this.getViewCompanyList();
              })
              .catch((err) => {
                console.log("debug log --> ", err);
              })
              .finally(() => {
                // 停止提交按钮的loading效果、关闭模态框、清空表单信息
                this.confirmLoading = false;
                this.showCertified = false;
                this.formCertified.resetFields();
              });
          } else {
            companyCertified(this.certifiedCompany)
              .then((res) => {
                this.getViewCompanyList();
              })
              .catch((err) => {
                console.log("debug log --> ", err);
              })
              .finally(() => {
                // 停止提交按钮的loading效果、关闭模态框、清空表单信息
                this.confirmLoading = false;
                this.showCertified = false;
                this.formCertified.resetFields();
              });
          }
        }
      });
    },
    // 上传图片
    beforeUpload(file) {
      const formData = new FormData();
      formData.append("files", file);
      uploadGeneralImg(formData)
        .then((res) => {
          this.certifiedCompany.fileUrl = res.data[0];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 点击认证按钮
    clickCertified() {
      this.certifiedCompany = {
        companyName: "",
        // 默认单选框选中企业
        organizationType: "0",
        organizationRegNo: "",
        legalName: "",
        fileUrl: "",
        email: ""
      };
      this.showCertified = true;
    },
    // 点击重新认证按钮
    reClickCertified(company) {
      this.certifiedCompany = company;
      this.certifiedCompany.organizationType = this.certifiedCompany.organizationType.toString();
      this.canEditEmail = false;
      this.canEditOrganizationRegNo = false;
      this.showCertified = true;
    },
    // 打开租户配额弹窗
    clickSiteTranche(site) {
      this.tranche = {
        id: site.id,
        currentContractCount: 0,
        currentFaceCount: 0
      };
      this.showSiteQuota = true;
    },
    // 关闭配额弹窗
    closeTranche() {
      this.showQuota = false;
      this.formTranche.resetFields();
    },
    // 关闭租户配额弹窗
    closeSiteTranche() {
      this.showSiteQuota = false;
      this.formSiteTranche.resetFields();
    },
    // 确认配额
    confirmTranche() {
      this.formTranche.validateFields((err, values) => {
        console.log("debug log --> ", values);
        if (!err) {
          this.confirmLoading = true;
          this.tranche.currentContractCount = values.contractTranche;
          this.tranche.currentFaceCount = values.facesTranche;
          console.log("debug log --> ", this.tranche);
          companyTranche(this.tranche)
            .then((res) => {
              this.getViewCompanyList();
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            })
            .finally(() => {
              // 停止提交按钮的loading效果、关闭模态框、清空表单信息
              this.confirmLoading = false;
              this.showQuota = false;
              this.formTranche.resetFields();
            });
        }
      });
    },
    // 确认配额
    confirmSiteTranche() {
      this.formSiteTranche.validateFields((err, values) => {
        console.log("debug log --> ", values);
        if (!err) {
          this.confirmLoading = true;
          this.siteTranche.currentContractCount = values.siteContractTranche;
          this.siteTranche.currentFaceCount = values.siteFacesTranche;
          console.log("debug log --> ", this.siteTranche);
          siteTranche(this.siteTranche)
            .then((res) => {
              this.selectSiteCount();
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            })
            .finally(() => {
              // 停止提交按钮的loading效果、关闭模态框、清空表单信息
              this.confirmLoading = false;
              this.showSiteQuota = false;
              this.formSiteTranche.resetFields();
            });
        }
      });
    },
    // 获取租户合同额度
    selectSiteCount() {
      getSiteCount()
        .then((res) => {
          this.contractSum = res.data.contractSum;
          this.contractCount = res.data.contractCount;
          this.faceSum = res.data.faceSum;
          this.faceCount = res.data.faceCount;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    }
  }
};
</script>
<style lang="scss">
.fix-item-wrapper2 {
  width: 60%;
  display: flex;
  height: 120px;
  background: #ffffff;
  border-radius: 8px;
  margin: auto;
  padding: 33px;
  border: 1px solid #e8e8e8;

  .remainderQuotaName {
    font-size: 14px;
    font-weight: 300;
    color: #9c9c9c;
  }

  .remainderQuota {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 500;
    color: #333333;
  }

  .fix-item-two {
    padding-left: 85px;
    margin-top: 10px;
    width: 50%;
    height: 45px;
    padding-right: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.body {
  padding: 25px;
}

.seal-table {
  .action {
    a {
      color: var(--primary);
    }
  }
}

.edit {
  color: var(--primary);
  cursor: pointer;
}

.license-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
